import 'package:dio/dio.dart' as dio;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/init.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/demand/request/ChangeDemandOrTaskRequestParams.dart';
import 'package:management/data/network/entity/demand/response/ListChildDemandOrTaskResponse.dart';
import 'package:management/data/network/entity/demand/response/ListLogDemandOrTaskResponse.dart'
    as log;
import 'package:management/element/InputField.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/showLogSheet.dart';
import 'package:management/element/toast.dart';
import 'package:management/generated/assets.dart';
import 'package:management/main.dart';
import 'package:management/page/ModuleMain/main_screen/logic.dart';
import 'package:management/page/ModuleProject/project_detail_screen/logic.dart';

import 'state.dart';

class DemandOrTaskDetailScreenLogic extends GetxController {
  final DemandOrTaskDetailScreenState state = DemandOrTaskDetailScreenState();

  @override
  void onInit() {
    super.onInit();
    _initData(false);
  }

  Future<void> refreshDemandOrTaskDetailPage() async {
    LoadingElement.loadingDialog(true);
    _initData(true);
  }

  getBg() {
    return AssetImage(state.listBg[state.demandId % 4]);
  }

  void _initData(bool isRefresh) async {
    await MyHttpClient.getDemandOrTaskDetail(state.demandId.toString())
        .then((value) {
      if (value.code == 200) {
        state.taskDetail.value = value.data!;
        if (state.taskDetail.value.description!.isEmpty) {
          state.taskDetail.value.description = MyText.trind.tr;
        }
        if (state.taskDetail.value.attachments != null) {
          state.listAttachment.value = state.taskDetail.value.attachments!;
          state.listAttachment.refresh();
        }
      } else {
        Get.back();
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
      return;
    });
    await MyHttpClient.getListChildDemandOrTask(state.demandId.toString())
        .then((value) {
      if (value.code == 200) {
        if (value.data != null) {
          state.listChildDemand.clear();
          state.listChildDemand.value = value.data!;
          state.listChildDemand.refresh();
        }
      } else {
        Get.back();
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
      return;
    });
    await MyHttpClient.getListLogDemandOrTask(state.demandId.toString())
        .then((value) {
      if (value.code == 200) {
        state.listLogDemand.clear();
        state.listLogDemand.value = value.data!;
        state.listLogDemand.refresh();
        if (isRefresh) Get.back();
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }

  changeStatus() {
    Get.bottomSheet(
        Wrap(
            children: List<Widget>.generate(5, (index) {
          return Container(
            padding: const EdgeInsets.symmetric(vertical: 2),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () {
                if (index == 4) {
                  Get.back();
                  return;
                }
                Get.back();
                _changeStatus(index);
              },
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    index == 4 ? MyText.cancel : state.listDemandState[index]!,
                    style: Theme.of(Get.context!).textTheme.bodyLarge?.copyWith(
                        color: index == 4
                            ? MyColor.error
                            : MyColor.grayScale[500]),
                  ),
                ],
              ),
            ),
          );
        })),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  changeEndTime() {
    var newDate = state.taskDetail.value.endTime;
    DatePicker.showDatePicker(Get.context!,
        showTitleActions: true,
        minTime: DateTime(2000, 1, 1),
        maxTime: DateTime(2099, 12, 31), onConfirm: (date) {
      newDate = '${date.year}-${date.month}-${date.day}';
      // state.taskDetail.value.endTime = newDate;
      _changeEndTime(date.toIso8601String());
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  changeName() {
    var newName = state.taskDetail.value.name;
    Get.defaultDialog(
        title: '请输入新的需求名',
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        content: MyTextField(
          controller: TextEditingController(text: newName),
          onChanged: (value) {
            newName = value;
          },
        ),
        onConfirm: () {
          Get.back();
          _changeName(newName);
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  changePriority() {
    Get.bottomSheet(
        Wrap(
            children: List<Widget>.generate(5, (index) {
          return Container(
            padding: const EdgeInsets.symmetric(vertical: 2),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () {
                if (index == 4) {
                  Get.back();
                  return;
                }
                Get.back();
                _changePriority(index);
              },
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    index == 4
                        ? MyText.cancel
                        : state.listDemandPriority[index]!,
                    style: Theme.of(Get.context!).textTheme.bodyLarge?.copyWith(
                        color: index == 4
                            ? MyColor.error
                            : MyColor.grayScale[500]),
                  ),
                ],
              ),
            ),
          );
        })),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  changeCharge() {
    LoadingElement.loadingDialog(true);
    MyHttpClient.getAllCompanyUser().then((value) {
      if (value.code == 200) {
        Get.back();
        var listNumbers = value.data!;
        Get.bottomSheet(
            Flexible(
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return SizedBox(
                    height: 50,
                    child: ListTile(
                      leading: ClipOval(
                        child: FadeInImage(
                          image: NetworkImage(listNumbers[index].avatar ??
                              GlobalInit.headImage),
                          height: 45.w,
                          width: 45.h,
                          fit: BoxFit.fill,
                          placeholderFit: BoxFit.scaleDown,
                          placeholder: const AssetImage(Assets.iconAvator),
                        ),
                      ),
                      title: Text(
                        listNumbers[index].nickname ?? MyText.loading,
                        style: Theme.of(Get.context!).textTheme.titleSmall,
                      ),
                      subtitle: Text(
                        listNumbers[index].realName ?? MyText.loading,
                        style: Theme.of(Get.context!).textTheme.bodyMedium,
                      ),
                      onTap: () {
                        _changeCharge(listNumbers[index].id);
                        Get.back();
                      },
                    ),
                  );
                },
                itemCount: listNumbers.length,
              ),
            ),
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
            backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }

  changeDescription() {
    var newDescription = state.taskDetail.value.description;
    Get.defaultDialog(
        title: MyText.demandDescription.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        content: MyTextField(
          controller: TextEditingController(text: newDescription),
          onChanged: (value) {
            newDescription = value;
          },
        ),
        onConfirm: () {
          Get.back();
          _changeDescription(newDescription);
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  _realChangeDemand(ChangeDemandOrTaskRequestParams params) {
    MyHttpClient.changeDemandOrTask(params).then((value) {
      if (value.code == 200) {
        refreshDemandOrTaskDetailPage();
        Get.find<MainScreenLogic>().getListByStatus();
        Get.find<ProjectDetailScreenLogic>().refreshProjectDetailPage();
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((e, p) {
      Utils.toastError(e);
    });
  }

  addTask(int i) {
    Get.toNamed(RouteConfig.createDemandScreen,
        arguments: {'pid': state.demandId, 'projectId': 0});
  }

  String getEndTime(String? endTime) {
    if (endTime == null) return '';
    if (endTime.isEmpty) return '';
    var time = DateTime.parse(endTime);
    return '${time.year}-${time.month}-${time.day}';
  }

  void seeMoreDemand(Data elementAt) {
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _deleteDemand(elementAt),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.deleteDemand.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _deleteDemand(Data elementAt) {
    Get.back();
    Get.defaultDialog(
        title: MyText.deleteProject.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        middleText: "${MyText.delete.tr}  ${elementAt.name} ?",
        middleTextStyle: Theme.of(Get.context!).textTheme.bodyLarge,
        onConfirm: () {
          Get.back();
          _realDeleteDemand(elementAt);
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _realDeleteDemand(Data elementAt) {
    MyHttpClient.deleteDemandOrTask(elementAt.id.toString()).then((value) {
      if (value.code == 200) {
        refreshDemandOrTaskDetailPage();
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  getFlagPriorityColor(num? priority) {
    if (priority == null) return Colors.transparent;
    switch (priority.toInt()) {
      case 0:
        return MyColor.grayScale[200];
      case 1:
        return MyColor.lightBlue;
      case 2:
        return MyColor.lightGreen;
      case 3:
        return MyColor.red;
    }
    return Colors.transparent;
  }

  seeDemandLog(num? id) {
    if (id == null) return;
    MyLogSheet.showLogSheet(id);
  }

  void jumpToNextDemand(num? id) {
    if (id == null) {
      return;
    }
    Get.toNamed(RouteConfig.demandOrTaskScreen,
        preventDuplicates: false, arguments: {'demandId': id});
  }

  void jumpToNextDemandByLog(log.Data listLogDemand) {
    if (listLogDemand.content == null) return;
    if (listLogDemand.content!.startsWith('创建')) {
      Get.toNamed(RouteConfig.demandOrTaskScreen,
          preventDuplicates: false,
          arguments: {'demandId': listLogDemand.relateDemandId});
    }
  }

  String logText1(log.Data listLogDemand) {
    if (listLogDemand.companyUser == null) {
      return '';
    }
    if (listLogDemand.companyUser?.nickName == null) {
      return '';
    }
    return '用户  ${listLogDemand.companyUser!.nickName!}  ${listLogDemand.content!}';
  }

  String logText2(log.Data listLogDemand) {
    if (listLogDemand.relateDemandName == null ||
        listLogDemand.createTime == null) {
      return '';
    }
    return '${listLogDemand.relateDemandName!}  ${listLogDemand.createTime!}';
  }

  seeAllLog(String? name) {
    Get.toNamed(RouteConfig.showMoreLogScreen,
        arguments: {'demandId': state.demandId, 'pName': name});
  }

  seeAllDemand(String? name) {
    Get.toNamed(RouteConfig.showMoreDemandScreen,
        arguments: {'demandId': state.demandId, 'pName': name});
  }

  void _changeStatus(int index) {
    var params =
        ChangeDemandOrTaskRequestParams(id: state.demandId, status: index);
    _realChangeDemand(params);
  }

  void _changeName(String? newName) {
    var params =
        ChangeDemandOrTaskRequestParams(id: state.demandId, name: newName);
    _realChangeDemand(params);
  }

  void _changeEndTime(String iso8601string) {
    var params = ChangeDemandOrTaskRequestParams(
        id: state.demandId, endTime: iso8601string);
    _realChangeDemand(params);
  }

  void _changePriority(int index) {
    var params =
        ChangeDemandOrTaskRequestParams(id: state.demandId, priority: index);
    _realChangeDemand(params);
  }

  void removeFile(num? id) {
    var deletes = <num>[];
    deletes.add(id!);
    var params = ChangeDemandOrTaskRequestParams(
        id: state.demandId, attachmentsDelete: deletes);
    state.listAttachment.removeWhere((element) => element.id == id);
    state.listAttachment.refresh();
    _realChangeDemand(params);
  }

  void addFiles() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      // allowedExtensions: ['docx', 'pdf', 'doc', 'ppt', 'pptx', 'txt', 'md'],
    );
    if (result != null) {
      state.listAttachFiles.value = result.files;
      state.listAttachFiles.refresh();
      _realAddFiles();
    } else {
      Utils.toastError('File not found');
    }
  }

  void _realAddFiles() async {
    LoadingElement.loadingDialog(true);
    if (state.listAttachFiles.isNotEmpty) {
      List<dio.MultipartFile> attachFiles = state.listAttachFiles
          .map((e) => dio.MultipartFile.fromFileSync(e.path!, filename: e.name))
          .toList();
      var listAttachAdds = <AttachmentsAdd>[];
      await MyHttpClient.uploadFiles(attachFiles).then((value) {
        if (value.code == 200) {
          Get.back();
          listAttachAdds = value.data!
              .map((e) => AttachmentsAdd(filename: e.name, url: e.url))
              .toList();
          var params = ChangeDemandOrTaskRequestParams(
              id: state.demandId, attachmentsAdd: listAttachAdds);
          _realChangeDemand(params);
        } else {
          Get.back();
          Utils.toastError(value.msg);
          return;
        }
      }).onError((error, stackTrace) {
        Get.back();
        Utils.toastError(error);
        return;
      });
    }
  }

  void _changeCharge(num? id) {
    var params =
        ChangeDemandOrTaskRequestParams(id: state.demandId, chargeId: id);
    _realChangeDemand(params);
  }

  void _changeDescription(String? newDescription) {
    var params = ChangeDemandOrTaskRequestParams(
        id: state.demandId, description: newDescription);
    _realChangeDemand(params);
  }
}
